package com.gitee.core.common.web;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


@Controller
@Scope("prototype")
@Slf4j
public class BaseController {


    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }


    @InitBinder
    protected final void initBinderInternal(WebDataBinder binder) {
        registerDefaultCustomDateEditor(binder);
        registerDefaultCustomNumberEditor(binder);
        initBinder(binder);
    }

    private void registerDefaultCustomNumberEditor(WebDataBinder binder) {
        // 注册双精度数字格式化类型: #0.00
        NumberFormat numberFormat = new DecimalFormat("#0.00");
        binder.registerCustomEditor(Double.class, new CustomNumberEditor(
                Double.class, numberFormat, true));
    }

    protected void registerDefaultCustomDateEditor(WebDataBinder binder) {
        // 注册默认的日期格式化类型: yyyy-MM-dd
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                dateFormat, true));
    }

    /**
     * 提供子类初始化表单, 子类如果要调用请重写该方法
     *
     * @param binder
     */
    protected void initBinder(WebDataBinder binder) {
    }


//    @ExceptionHandler({Exception.class})
//    public void exceptionHandler(Exception e, HttpServletResponse response) {
//        log.error(e.getMessage());
//    }


    public Map<String, Object> getRequestFormMap(HttpServletRequest request) throws UnsupportedEncodingException {
        String str = getRequestParams(request);
        Map<String, Object> params = new HashMap<String, Object>();
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();

            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    params.put(paramName, paramValue);
                }
            }
        }
        if (StringUtils.isNotBlank(str) && params.size() == 0) {
            String str1 = java.net.URLDecoder.decode(str, "UTF-8");
            String[] strs = str.split("name=");
            String[] strs1 = str1.split("&");
            for (int i = 1; i < strs.length; i++) {
                String temp = strs[i].substring(0, strs[i].indexOf("------"));
                int index = temp.indexOf("\"", 1);
                index = index + 1;
                String key = temp.substring(0, index);
                String value = temp.substring(index, temp.length());
                params.put(key, value);
            }
            for (int i = 0; i < strs1.length; i++) {
                String[] temp = strs1[i].split("=");
                params.put(temp[0], temp[1]);
            }
        }
        return params;
    }

    /**
     * 使用 request.getInputStream()读取回调数据流
     *
     * @param request
     * @return
     */
    public String getRequestParams(HttpServletRequest request) {
        String params = "";
        try {
            request.setCharacterEncoding("UTF-8");
            InputStream in = request.getInputStream();
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            params = sb.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return params;
    }

}
